#include<netinet/in.h>
#include<string.h>
#include<arpa/inet.h>
#include<sys/types.h>
#include<sys/select.h>
#include<sys/socket.h>
#include<fcntl.h>
#include "log.hpp"
class Sock
{
public:
  static int Socket()
  {
    int listen_sock = socket(AF_INET,SOCK_STREAM,0);
    int f1 = fcntl(listen_sock,F_GETFL);
    fcntl(listen_sock,F_SETFL,f1 | O_NONBLOCK);
    if(listen_sock >= 0) 
    {
      LOG(NORMAL) << "套接字创建成功!" << endl;
      return listen_sock;
    }
    else
    {
      LOG(FATAL) <<"套接字创建失败!" << endl;
      exit(1);
    }
    
  }
  
  static void Bind(int listen_sock,uint16_t port)
  {
    struct sockaddr_in local;
    socklen_t len = sizeof(local);
    memset(&local,0,len);
    local.sin_family = AF_INET; 
    local.sin_port = htons(port);
    local.sin_addr.s_addr = INADDR_ANY;
    if(bind(listen_sock,(struct sockaddr*)&local,len) < 0) 
    {
      LOG(FATAL) <<"绑定失败" << endl;
      exit(2);
    }
    LOG(NORMAL) <<"绑定成功" << endl;
  }
  static void Listen(int listen_sock)
  {
    if(listen(listen_sock,5) < 0)
    {
      LOG(FATAL) <<"监听状态设置失败" << endl;
      exit(3);
    } 
    LOG(NORMAL) <<"监听状态设置成功"<<endl;
  }
  static int Accept(int listen_sock)
  {
    struct sockaddr_in peer;
    memset(&peer,0,sizeof(peer));
    socklen_t len = 0;
    int sock = accept(listen_sock,(struct sockaddr*)&peer,&len);
    if(sock >= 0)
    {
      uint16_t port = ntohs(peer.sin_port); 
      string ip = inet_ntoa(peer.sin_addr); 
      LOG(NOMAL) <<"新连接的ip："<<ip <<"  port:" << port<<endl;  
      return sock;
    } 
    else 
    {
      LOG(NOMAL) <<"获取链接失败" << endl;
      exit(4);
    }
  }
};

